package com.theaf.basemodule.service.impl.core;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.theaf.basemodule.common.api.DicService;
import com.theaf.basemodule.common.vo.dic.DicVO;
import com.theaf.basemodule.service.impl.DicServiceImpl;
import com.theaf.core.api.DicComService;
import com.theaf.core.api.model.DicData;
import com.theaf.core.api.model.DicType;
import com.theaf.core.cache.RedisHelper;
import com.theaf.core.utils.BeanMapper;
import com.theaf.core.utils.LogUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:songwenke
 * @Description:字典外部服务
 * @Date:create in 11:30 2017/12/28
 * @Modified By:
 **/
@Service
public class DicServiceDubboImpl implements DicComService {
    private LogUtils log= LogUtils.getLog(DicServiceDubboImpl.class);

    @Resource
    private DicService dicService;


    @Override
    public DicType findDicTypeByTag(String tag) {
        DicType dicType = null;
        // 从缓存中获取城市信息
        String key = DicServiceImpl.CACHE_PREFIX + tag;
        dicType = (DicType) RedisHelper.get(key);
        if(dicType==null){
            DicVO dicVO = dicService.findByTag(tag);
            if(dicVO==null){
                return null;
            }
            dicType = BeanMapper.map(dicVO,DicType.class);
            dicType.setData(BeanMapper.mapList(dicVO.getDatas(), DicData.class));
            RedisHelper.set(key,dicType,null);
        }
        return dicType;
    }

    @Override
    public List<DicData> findDicDataByTypeTag(String tag) {
        DicType dicType = findDicTypeByTag(tag);
        if(dicType==null){
            return  new ArrayList();
        }
        return dicType.getData();
    }

    @Override
    public DicData findDicDataByKey(String tag, String key) {
        List<DicData> datas = findDicDataByTypeTag(tag);
       return datas.stream().filter(e -> StringUtils.equals(key,e.getCode())).findAny().get();
    }

    @Override
    public String findDicDataNameByKey(String tag, String key) {
        return findDicDataByKey(tag,key).getName();
    }

    @Override
    public String findDicDataMemoByKey(String tag, String key) {
        return findDicDataByKey(tag,key).getRemark();
    }
}
